<?php

namespace app\api\controller;

use app\api\services\OrderService;
use ba\Exception;
use think\facade\Db;
use Throwable;
use ba\PayLib;
use think\facade\Log;
use Yansongda\Pay\Pay;
use app\common\controller\Frontend;
use Psr\Http\Message\ResponseInterface;

class PayNotify extends Frontend
{
    protected array $noNeedLogin = ['wechat', 'alipay'];
    protected array $noNeedPermission = ['*'];

    /**
     * 允许跨域
     * @throws Throwable
     */
    public function initialize (): void
    {
        header('Access-Control-Allow-Credentials: true');
        header('Access-Control-Max-Age: 1800');
        header('Access-Control-Allow-Methods: *');
        header('Access-Control-Allow-Headers: *');
        header('Access-Control-Allow-Origin: *');
        parent::initialize();
    }

    /**
     * 微信支付回调
     * @throws Throwable
     */
    public function wechat (): ResponseInterface
    {
        Db::startTrans();
        try {
            Pay::config(PayLib::getConfig());

            $result = Pay::wechat()->callback();

            Log::write('收到回调数据：' . json_encode($result));
            if ($result['event_type'] != 'TRANSACTION.SUCCESS') {
                throw new Exception('支付失败 - ' . json_encode($result));
            }

            #支付交易流水号
            $transaction_id = $result['resource']['ciphertext']['transaction_id'];
            #系统订单号
            $out_trade_no = $result['resource']['ciphertext']['out_trade_no'];
            #自定义标识 orderPay 正常下单 recharge 钱包充值 add_clock_service 加钟订单
            $attach = $result['resource']['ciphertext']['attach'];
            #用户支付金额 分 处理为元
            $payer_total = bcdiv($result['resource']['ciphertext']['amount']['payer_total'], 100, 2);

            #支付成功时间
            $success_time_rfc = $result['resource']['ciphertext']['success_time'];
            $success_time = date('Y-m-d H:i:s', strtotime($success_time_rfc));

            $orderServiceClass = (new OrderService($out_trade_no, $transaction_id, $attach, $payer_total, $success_time));

            #记录回调日志
            Db::name('pay_callback')->insert([
                'order_sn' => $out_trade_no,
                'callback' => json_encode($result),
                'type'     => $attach
            ]);
            #处理回调
            $ret = $orderServiceClass->$attach();
            Db::commit();
        } catch (Throwable $e) {
            Db::rollback();
            echo "走异常了";
            Log::error('支付回调异常- ' . $e->getMessage());
        }
        // return 'success';
        return Pay::wechat()->success();
    }

    /**
     * 支付宝支付回调
     * @throws Throwable
     */
    public function alipay (): ResponseInterface
    {
        try {
            Pay::config(PayLib::getConfig());

            $result = Pay::alipay()->callback();

            Log::write('收到回调数据：' . json_encode($result));
        } catch (Throwable $e) {
            Log::write('支付回调异常' . $e->getMessage());
        }

        return Pay::alipay()->success();
    }


}